package nccloud.sso.filter;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import nc.bs.logging.Logger;
import nccloud.sso.util.DesUtil;
import nccloud.sso.util.SSOUtils;

public class SSOSecurityFilter extends HttpFilter {

	@Override
	protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try {
//			String ticket = "TvhCMCLuien5uBFZvDZL0nk0AF9InuwWofpl9AlrJPGx5OIKAwsXwqlYyxLMMtNn";
			String ticket = request.getParameter("ticket");
			Logger.info("ticket:"+ticket);
			Properties properties = SSOUtils.getNCHomeProperties();
//			String token = request.getParameter("token");
			if (ticket != null) {//单点登录解码+校验
//				token = token.replace(" ", "+");
//				if (!isValidity(request.getParameter("usercode"), request.getParameter("ts"),
//						AESUtil.decode(token).split("\\|"))) throw new IllegalAccessError("非法访问！");
//				request.setAttribute("usercode", request.getParameter("usercode"));
//				Properties properties = SSOUtils.getNCHomeProperties();
//				String publickey = properties.getProperty("publickey");
				String usercode = checkUserCode(ticket);
				request.setAttribute("usercode",usercode);
				chain.doFilter(request, response);
			}else {
				String referer = request.getHeader("Referer"); 
				if(request.getParameter("c")!=null && request.getParameter("c").toString().length()>0)
				{
					//如果是单点登录
					request.setAttribute("srcType", referer == null ? 1 : 2);
					request.setAttribute("pk_message", request.getParameter("pk_message"));
					request.setAttribute("pk_bill", request.getParameter("pk_bill"));
					request.setAttribute("c", request.getParameter("c")); 
					request.setAttribute("p", request.getParameter("p"));
					request.setAttribute("tradetype", request.getParameter("tradetype"));
					
					request.setAttribute("usercode", request.getParameter("usercode"));
					chain.doFilter(request, response);
				}
				else
				{
					//从登陆界面跳转到统一认证平台登陆
					String iDassUrl = properties.getProperty("iDassUrl");
//					iDassUrl = "http://124.223.64.58:9001/";
//					HttpSession session=request.getSession();
//					String aString =(String) session.getAttribute("loginUser");
//					Cookie[] cookies=request.getCookies();
//					  if(cookies!=null){
//					      for(int i=0;i<cookies.length;i++){
//					          if(cookies[i].getName().equals("namepsd")){
//					          //这里读的时候也记得转换编码，否则读出来会是乱码
//					          //split（）是截取String型的方法
//					          //在jsp中使用这个方法需要导入java.net.*，在最上面写
//					        String username=URLDecoder.decode(cookies[i].getValue(), "UTF-8").split("-")[0];
//					            String  userpsd=URLDecoder.decode(cookies[i].getValue(), "UTF-8").split("-")[1];
//					         System.out.println("qq");
//					          }
//					      }
//					  }
					iDassUrl = iDassUrl+"sso/auth?redirect=http://61.181.83.178:1666/nccloud/sso/visit.action";
					response.sendRedirect(iDassUrl);
				}
			}
		} catch (Exception e) {
			response.setStatus(403);
			this.recordError(e);
		}
	}

	/**
	 * 校验token（仅限与单点登录） token 组成 usercode +"|"+ts+"|"+盐值
	 * 
	 * @param usercode
	 * @param ts
	 * @param _params
	 * @return
	 */
	private boolean isValidity(String usercode, String ts, String[] _params) {
		return usercode != null && usercode.equals(_params[0]) && ts != null && ts.equals(_params[1])
				&& DesUtil.KEY.equals(_params[2]);
	}

	/**
	 *
	 * 错误日志记录
	 * @param e
	 */
	private void recordError(Exception e) {
		Logger.error("SSO::AESSecurityFilter.doFilter");
		Logger.error(e.getMessage());
		Logger.error("SSO::调用栈");
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw, true));
		Logger.error(sw.getBuffer().toString());
	}

	/**
	 * 解析id_token 获取usercode
	 * @param ticket
	 * @return
	 * @throws Exception
	 */
	private String checkUserCode(String ticket) throws Exception {
		
		Properties properties = SSOUtils.getNCHomeProperties();
		Logger.info("获取用户信息");
		String iDassUrl = properties.getProperty("iDassUrl");
		String client_id = properties.getProperty("client_id");
		String secretkey = properties.getProperty("secretkey");
		String ssoLogoutCall = properties.getProperty("ssoLogoutCall");
		String url = iDassUrl+"sso/doLoginByTicket?ticket="+ticket
				+"&client_id="+client_id+"&secretkey="+secretkey
				+ "&ssoLogoutCall="+ssoLogoutCall;
//		String url = "http://124.223.64.58:9000/sso/doLoginByTicket?ticket="+ticket
//				+"&client_id="+client_id+"&secretkey="+secretkey
//				+ "&ssoLogoutCall="+ssoLogoutCall;
//		ticket：单点登录授权后返回的票据    checkTicket
//		ssoLogoutCall：应用注销地址(此接口由业务系统实现，传入参数 cvaToken 和 loginId)
//		client_id：应用编码（在应用管理中注册后，编制的应用编码）
//		secretkey：应用服务秘钥
		String result = SSOUtils.sendUamPost(url, "获取统一认证用户");
//		String result = SSOUtils.request(url,"", "GET");
		if(!"".equals(result)&&result!=null) {
			JSONObject parseObject = JSONObject.parseObject(result);
			Object object = parseObject.get("loginId");
//			String object = "yy9";
			if(!"".equals(object)&&object!=null) {
//				IMDPersistenceQueryService service = (IMDPersistenceQueryService) NCLocator.getInstance().lookup(IMDPersistenceQueryService.class.getName());
////				IMDPersistenceQueryService service = ServiceLocator.find(IMDPersistenceQueryService.class); 
//				Collection<UserVO> userVOList = service.queryBillOfVOByCond(UserVO.class, "pk_psndoc = '"+object.toString()+"' and dr=0", false);
//				for (UserVO userVO : userVOList) {
					return object.toString();
//				}
			}
		}
		return "";
    }
}
